/**
 * Authentication utility functions
 */

// Check if user is logged in based on token presence
export const isAuthenticated = () => {
  return localStorage.getItem('token') !== null;
};

// Get user token
export const getToken = () => {
  return localStorage.getItem('token');
};

// Set user token and additional data if needed
export const setAuth = (token, userData = null) => {
  localStorage.setItem('token', token);
  if (userData) {
    localStorage.setItem('user', JSON.stringify(userData));
  }
};

// Clear all authentication data
export const clearAuth = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
};

// Get currently logged in user data if available
export const getCurrentUser = () => {
  const user = localStorage.getItem('user');
  return user ? JSON.parse(user) : null;
};

// Parse JWT token (without validation - for basic info only)
export const parseJwt = (token) => {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map((c) => {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        })
        .join('')
    );
    return JSON.parse(jsonPayload);
  } catch (error) {
    return null;
  }
};

// Check if token is expired
export const isTokenExpired = () => {
  const token = getToken();
  if (!token) return true;
  
  const decodedToken = parseJwt(token);
  if (!decodedToken) return true;
  
  // exp is in seconds, Date.now() is in milliseconds
  return decodedToken.exp * 1000 < Date.now();
}; 